package com.tsingteng.cosfun.ui.cosfun;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dingmouren.layoutmanagergroup.viewpager.OnViewPagerListener;
import com.dingmouren.layoutmanagergroup.viewpager.ViewPagerLayoutManager;
import com.pili.pldroid.player.IMediaController;
import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.base.BasePresenterFragment;
import com.tsingteng.cosfun.bean.BlindResp;
import com.tsingteng.cosfun.bean.EventBean;
import com.tsingteng.cosfun.bean.FollowBean;
import com.tsingteng.cosfun.bean.FoundAtBean;
import com.tsingteng.cosfun.bean.HomeBean;
import com.tsingteng.cosfun.bean.JoinCostarBean;
import com.tsingteng.cosfun.bean.OpusBean;
import com.tsingteng.cosfun.bean.RecommenResp;
import com.tsingteng.cosfun.bean.VideoSection;
import com.tsingteng.cosfun.callback.AppListener;
import com.tsingteng.cosfun.common.Constant;
import com.tsingteng.cosfun.common.Navigate;
import com.tsingteng.cosfun.helper.VideoHelper;
import com.tsingteng.cosfun.http.Url;
import com.tsingteng.cosfun.ui.cosfun.adapter.OpusAdapterNew;
import com.tsingteng.cosfun.ui.cosfun.contract.OpusContract;
import com.tsingteng.cosfun.ui.cosfun.contract.ZanContract;
import com.tsingteng.cosfun.ui.cosfun.cosinterface.ObserverListener;
import com.tsingteng.cosfun.ui.cosfun.cosinterface.ObserverManager;
import com.tsingteng.cosfun.ui.cosfun.cosinterface.RecyclerOnScrollListener;
import com.tsingteng.cosfun.ui.cosfun.presenter.OpusPresenter;
import com.tsingteng.cosfun.ui.mine.HomeMineFragment;
import com.tsingteng.cosfun.ui.mine.TerminalActivity;
import com.tsingteng.cosfun.utils.AppUtils;
import com.tsingteng.cosfun.utils.ImageUtils;
import com.tsingteng.cosfun.utils.KeywordUtil;
import com.tsingteng.cosfun.utils.LogUtils;
import com.tsingteng.cosfun.utils.LogonUtils;
import com.tsingteng.cosfun.utils.NetUtils;
import com.tsingteng.cosfun.utils.NotchUtil;
import com.tsingteng.cosfun.utils.ShareUtils;
import com.tsingteng.cosfun.utils.StringUtils;
import com.tsingteng.cosfun.utils.VideoUtils;
import com.tsingteng.cosfun.widget.MyRecycleView;
import com.tsingteng.cosfun.widget.dialog.DownLoadProgressDialog;
import com.tsingteng.cosfun.widget.dialog.LongPressShowDialog;
import com.tsingteng.cosfun.widget.dialog.ProgressDialog;
import com.tsingteng.cosfun.widget.dialog.ShowNetStatusDialog;
import com.tsingteng.cosfun.widget.view.MySwipeRefreshLayout;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

public class OpuslFragmentNew extends BasePresenterFragment<OpusPresenter, OpusContract.IOpusView> implements ObserverListener, OpusContract.IOpusView, ZanContract.IZanView, OpusAdapterNew.OnItemClickLisenter, ShareFragment.OnShareItemClickLisenter, ShareUtils.ShareListener, ShowNetStatusDialog.OnItemClickListener, LongPressShowDialog.OnItemClickListener, CommentListDialogFragment.CommLisenter
        , OpusAdapterNew.ActivityClickListener ,View.OnClickListener{
    private String TAG = this.getClass().getSimpleName();
    private RecyclerView recyclerView = null;
    private ViewPagerLayoutManager mLayoutManager;
    private OpusAdapterNew mAdapter;
    private int pageNo = 1;
    private int currentPosition = 0;
    private int lastPosition = 0;
    private List<OpusBean> videoList = null;
    private DownLoadProgressDialog.Builder builder = null;
    private DownLoadProgressDialog downLoadProgressDialog = null;
    private ArrayList<String> urlPath;
    private ProgressBar progressBar = null;
    private ProgressBar v_progressBar = null;
    private IMediaController.MediaPlayerControl mPlayer;
    private static final int SHOW_PROGRESS = 2;
    private AudioManager audio = null;
    private ShowNetStatusDialog.Builder netBuilder = null;
    private ShowNetStatusDialog netStatusDialog = null;
    private boolean canPlay = false;
    private List<VideoSection> videoSectionList = null;

    private RelativeLayout cosRel = null;
    private CircleImageView cosCircleImageView = null;
    private CircleImageView opus_item_view_user_img1 = null;
    private ImageView cosGuanzhu = null;
    private TextView cosTag = null;

    private LongPressShowDialog.Builder longBulider;
    private LongPressShowDialog longPressShowDialog;

    private MySwipeRefreshLayout refreshLayout = null;
    private boolean isRefresh = false;
    private String isBroad;
    boolean isToLogon = false;
    private ColorMatrixColorFilter grayColorFilter = null;
    private ImageView back = null;

    private int videoPlayCount = 0;
    private int videoPlayTimes = 0;
    private int lastPlayTimes = 0;
    private boolean isCanClickJoin = true;//是否可以点击合拍按钮
    private ProgressDialog progressDialog;
    private OpusBean mOpusBean;
    boolean mGuanZhu = false;
    List<OpusBean> coverImgUrl = null;
    private int manager;
    private String[] mProfileId;

    @Override
    protected void initView() {
        super.initView();
        NotchUtil.setWindowTrans(getActivity(), true, false);
        recyclerView = rootView.findViewById(R.id.opus_list);
        progressBar = rootView.findViewById(R.id.play_progress);
        v_progressBar = rootView.findViewById(R.id.volume_progress);
        ImageView imageView = rootView.findViewById(R.id.cosfun_iv);
        if (0==LogonUtils.getIsAdmin()) {
            imageView.setVisibility(View.VISIBLE);
        }else if (1==LogonUtils.getIsAdmin()){
            imageView.setVisibility(View.GONE);
        }
        imageView.setOnClickListener(this);
        mLayoutManager = new ViewPagerLayoutManager(getActivity(), OrientationHelper.VERTICAL);
        videoList = new ArrayList<>();
        videoSectionList = new ArrayList<>();
        urlPath = new ArrayList<>();
        mAdapter = new OpusAdapterNew(getActivity(), 1, videoList, currentPosition, this);
        mAdapter.setActivityListener(this);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setAdapter(mAdapter);
        initListener();
        ObserverManager.getInstance().add(this);
        back = rootView.findViewById(R.id.back);
        back.setVisibility(View.INVISIBLE);
        refreshLayout = rootView.findViewById(R.id.fragment_opus_refresh);
        AppListener.getInstance().setOnRefreshBackListener(new AppListener.OnRefreshBackListener() {
            @Override
            public void OnReresh(String isBroads) {
                playerPause(currentPosition);
                isRefresh = true;
                isBroad = isBroads;
                pageNo = 1;
//                OpusBean opusBean = (OpusBean) intent.getSerializableExtra("result");
                if (isAdded()) {
                    mPresenter.getOpusList(pageNo + "");
                } else {
                    mAdapter.notifyDataSetChanged();
                }
            }
        });
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (null != coverImgUrl) {
                    refreshLayout.setRefreshing(false);
                    return;
                }
                playerPause(currentPosition);
                isRefresh = true;
                pageNo = 1;
                mPresenter.getOpusList(pageNo + "");
            }
        });
        AppListener.getInstance().setOnPublishVideoBackListener(new AppListener.OnPublishVideoBackListener() {
            @Override
            public void OnVideoBack(OpusBean opusBean) {
                addMyVideo(opusBean);
            }
        });

        builder = new DownLoadProgressDialog.Builder(getActivity(), getActivity());
        netBuilder = new ShowNetStatusDialog.Builder(getActivity(), getActivity());
        longBulider = new LongPressShowDialog.Builder(getActivity(), getActivity());
        setState(OpusAdapterNew.FooterState.Normal);
        recyclerView.addOnScrollListener(onScrollListener);
        audio = (AudioManager) getActivity().getSystemService(Service.AUDIO_SERVICE);

        ColorMatrix cm = new ColorMatrix();
        cm.setSaturation(0); // 设置饱和度
        grayColorFilter = new ColorMatrixColorFilter(cm);

        //增加下载弹出框
        progressDialog = new ProgressDialog(getActivity());
//        rootView.findViewById(R.id.add).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//
//            }
//        });
        if (null != coverImgUrl) {
            back.setVisibility(View.VISIBLE);
            back.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    getActivity().finish();
                }
            });
            if (currentPosition > 0 && currentPosition < coverImgUrl.size()) {
                mLayoutManager.scrollToPositionWithOffset(currentPosition, 0);
                mLayoutManager.setStackFromEnd(true);
            }
            if (!NetUtils.isNetworkAvailable()) {
                showNetType(1, "网络连接错误", "刷新 ");
                return;
            }
            play();
        }
    }

    protected OpusAdapterNew.FooterState mState = OpusAdapterNew.FooterState.Normal;

    protected void setState(OpusAdapterNew.FooterState mState) {
        this.mState = mState;
        (getActivity()).runOnUiThread(() -> changeAdaperState());
    }

    //改变底部bottom的样式
    protected void changeAdaperState() {
        if (mAdapter != null && mAdapter.mFooterHolder != null) {
            mAdapter.mFooterHolder.setStatus(mState);
        }
    }

    @Override
    protected void getBundle(Bundle bundle) {
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_opus;
    }

    @Override
    public void onPause() {
        super.onPause();
        playerPause(currentPosition);
        if (videoList==null || videoList.size()==0) return;
        ObserverManager.getInstance().notifyObserver(ObserverListener.EVENT_CHANGE_OPUS, currentPosition, videoList.get(currentPosition).getProfileId());

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        playerPause(currentPosition);
    }

    @Override
    protected void initData(View rootView) {
        if (!NetUtils.isNetworkAvailable()) {
            showNetType(1, "网络连接错误", "刷新 ");
            return;
        }
        mPresenter.getOpusList(pageNo + "");
    }

    @Override
    protected OpusPresenter createPresenter() {
        return new OpusPresenter();
    }

    @Override
    protected View initHeader() {
        return null;
    }

    @Override
    protected MyRecycleView createRecycleView() {
        return null;
    }

    @Override
    protected BaseQuickAdapter createAdapter() {
        return null;
    }

    @Override
    protected void refresh() {
    }

    private void initListener() {
        mLayoutManager.setOnViewPagerListener(new OnViewPagerListener() {
            @Override
            public void onPageRelease(boolean isNext, int position) {
                lastPosition = position;
                lastPlayTimes = videoPlayTimes;
                if (position < videoList.size()) {
                    sendGrade(videoList.get(position).getId() + "", lastPlayTimes * videoPlayCount);
                }
                playerPause(lastPosition);
            }

            @Override
            public void onPageSelected(int position, boolean isBottom) {
                try {
                    currentPosition = position;
                    progressBar.setProgress(0);
                    getCosView();
                    getCostarList();

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onLayoutComplete() {
            }

        });
    }

    RecyclerOnScrollListener onScrollListener = new RecyclerOnScrollListener() {
        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);
            if (null != coverImgUrl) {
                return;
            }
            if (mAdapter.mFooterHolder.status == OpusAdapterNew.FooterState.TheEnd) {
                Toast.makeText(getActivity(), "已经是最后一条了", Toast.LENGTH_SHORT).show();
                return;
            }
            setState(OpusAdapterNew.FooterState.Loading);
            pageNo++;
            mPresenter.getOpusList(pageNo + "");
        }

        @Override
        public void onScrolling(View view) {
            super.onScrolling(view);

        }

        @Override
        public void onScrollStop(View view) {
            super.onScrollStop(view);
            play();
        }

    };

    public void play() {
        if (!canPlay && !NetUtils.isWiFi()) {
            showNetType(0, "非wifi环境不播放视频", "还是想看");
            playerPause(currentPosition);
            return;
        }
        if (videoList == null || 0 == videoList.size()) {
            return;
        }
//        ObserverManager.getInstance().notifyObserver(ObserverListener.EVENT_CHANGE_OPUS, currentPosition, videoList.get(currentPosition).getProfileId());
        getCostarList();
        if (mAdapter != null) {
            mHandler.removeMessages(10001);
            mHandler.sendEmptyMessageDelayed(10001, 200);
            return;
        }

        EventBean eventBean = new EventBean();
        eventBean.setPosition(currentPosition);
        eventBean.setType(1);
        EventBus.getDefault().post(eventBean, OpusAdapterNew.EVENT_START);
    }

    //播放暂停
    public void playerPause(int position) {
        if (mAdapter != null) {
            mAdapter.stopPlay(position);
            return;
        }
        EventBean eventBean = new EventBean();
        eventBean.setType(1);
        eventBean.setPosition(currentPosition);
        EventBus.getDefault().post(eventBean, OpusAdapterNew.EVENT_PAUSE);
    }

    @Override
    public void onMultiWindowModeChanged(boolean isInMultiWindowMode) {
        super.onMultiWindowModeChanged(isInMultiWindowMode);
        if (isInMultiWindowMode && Build.VERSION.SDK_INT >= 19) {
            View decorView = getActivity().getWindow().getDecorView();
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
    }

    @Override
    public void longPress(int position, OpusBean opusBean) {
        if (opusBean.getProfileId() == LogonUtils.getProFildId()) {
            longPressShowDialog = longBulider.setMessage(position, opusBean, 1).setItemClickListener(this).createDialog();
            longPressShowDialog.show();
        } else {
            longPressShowDialog = longBulider.setMessage(position, opusBean, 0).setItemClickListener(this).createDialog();
            longPressShowDialog.show();
        }

    }

    @Override
    public void showPlayProgress(int position, IMediaController.MediaPlayerControl mediaPlayerControl) {
        if (currentPosition == position) {
            videoPlayCount++;
        } else {
            videoPlayCount = 1;
            videoPlayTimes = 0;
        }
        mPlayer = mediaPlayerControl;
        mHandler.removeMessages(SHOW_PROGRESS);
        mHandler.sendEmptyMessageDelayed(SHOW_PROGRESS, 100);
    }


    private void changeZan(boolean type, int index) {
        if (recyclerView == null || videoList.size() == 0) {
            return;
        }
        View itemView = recyclerView.getChildAt(0);
        if (itemView == null || videoList.size() == 0) {
            return;
        }
        final TextView likeView = itemView.findViewById(R.id.opus_item_view_like);
        final ImageView img = itemView.findViewById(R.id.opus_item_view_like_img);
        int count = 0;
        count = videoList.get(index).getLikeCount();
        if (type) {
            count++;
            videoList.get(index).setIsLike(1);
        } else {
            count--;
            videoList.get(index).setIsLike(-1);
        }
        likeView.setText(StringUtils.formatZanCount(count));

        if (videoList.get(index).getIsLike() == 1) {
            img.setImageDrawable(getActivity().getResources().getDrawable(R.drawable.great_pink_icon));
        } else {
            img.setImageDrawable(getActivity().getResources().getDrawable(R.drawable.great_icon));

        }
        videoList.get(index).setLikeCount(count);
    }

    //获取合演view
    public void getCosView() {
        if (recyclerView == null || videoList.size() == 0) {
            return;
        }
        View itemView = recyclerView.getChildAt(0);
        if (itemView == null) {
            return;
        }
        cosRel = itemView.findViewById(R.id.opus_item_view_user_join_rel);
        cosCircleImageView = itemView.findViewById(R.id.opus_item_view_user_join);
        opus_item_view_user_img1 = itemView.findViewById(R.id.opus_item_view_user_img1);
        cosGuanzhu = itemView.findViewById(R.id.opus_item_view_user_joi_guanzhu);
        cosTag = itemView.findViewById(R.id.opus_item_view_user_join_des);
    }

    @Override
    public void observerUpData(int eventType, int index, int id) {
        switch (eventType) {
            case ObserverListener.EVENT_ZAN_ADD://点赞
                if (videoList.get(index).getIsLike() == 1) {
                    return;
                }
                mPresenter.getOpusZan(videoList.get(currentPosition).getId() + "", "1", "", "1");
                changeZan(true, currentPosition);
                break;
            case ObserverListener.KEYCODE_VOLUME_UP://音量加
                KeywordUtil.matchTxt();
                int max_volume = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
                int cu_volume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
                v_progressBar.setVisibility(View.VISIBLE);
                v_progressBar.setMax(max_volume);
                v_progressBar.setProgress(cu_volume);
                Log.e("volume", "-----add max_volume=" + max_volume);
                Log.e("volume", "-----add cu_volume=" + cu_volume);
                mHandler.removeMessages(100);
                mHandler.sendEmptyMessageDelayed(100, 3000);
                break;
            case ObserverListener.KEYCODE_VOLUME_DOWN://音量减
                max_volume = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
                cu_volume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
                Log.e("volume", "-----jian max_volume=" + max_volume);
                Log.e("volume", "-----jian cu_volume=" + cu_volume);
                v_progressBar.setVisibility(View.VISIBLE);
                v_progressBar.setMax(max_volume);
                v_progressBar.setProgress(cu_volume);
                mHandler.removeMessages(100);
                mHandler.sendEmptyMessageDelayed(100, 3000);
                break;
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

    }

    @Override
    public void onLoadMoreRequested() {

    }


    @Override
    public void showLogonResult(HomeBean.DataBean dataBean) {
        if (dataBean == null || dataBean.getData() == null || dataBean.getData().size() == 0) {
            setState(OpusAdapterNew.FooterState.TheEnd);
        } else {
            if (isRefresh) {
                isRefresh = false;
                videoList.clear();
            }
            Log.i("--fff--", dataBean.getData() + "");
            videoList.addAll(dataBean.getData());
            if (videoList.size() == dataBean.getTotal()) {
                setState(OpusAdapterNew.FooterState.TheEnd);
            }
        }
        mAdapter.notifyDataSetChanged();
        refreshLayout.setRefreshing(false);
        if (TextUtils.isEmpty(isBroad)) {
            mHandler.sendEmptyMessageDelayed(10000, 300);
        } else {
            isBroad = "";
        }

    }

    @Override
    public void showSendResult(int type) {
        if (type == 2) {
            Toast.makeText(getActivity(), "已标记不喜欢", Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    public void showFail(String msg) {
        super.showFail(msg);
        isCanClickJoin = true;
    }

    @Override
    public void showCostarVideoResult(JoinCostarBean joinCostarBean) {
        LogUtils.e(TAG, "开始下载:showCostarVideoResult");
        VideoHelper.getIntence().downVideo(getContext(),mOpusBean.getIsActivity(), joinCostarBean, new VideoHelper.OnVideoHelperDowmVideoListener() {
            @Override
            public void onStartDown() {
                if (progressDialog == null) progressDialog = new ProgressDialog(getActivity());
                progressDialog.show();
                isCanClickJoin = true;
            }

            @Override
            public void onPregress(int pregress) {
                progressDialog.setmProgressbar(pregress);
            }

            @Override
            public void onComplete() {
                progressDialog.disMissDialog();
                VideoHelper.getIntence().setmOpusBean(mOpusBean);
                if ("1".equals(mOpusBean.getIsActivity())) {
                    VideoHelper.getIntence().setActivityId(mOpusBean.getActivityId());
                    Navigate.gotoCostar(getActivity(), mOpusBean.getActivityId());
                } else {
                    VideoHelper.getIntence().setActivityId(-1);
                    Navigate.gotoCostar(getActivity(), -1);
                }
                isCanClickJoin = true;
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        isToLogon = false;
    }

    @Override
    public void getFollowResult(FollowBean followBean) {
        switch (followBean.getRelationType()) {
            case 0:
                break;
            case 1:
                Toast.makeText(getActivity(), "已关注", Toast.LENGTH_SHORT).show();
                if (!mGuanZhu) {
                    ShowGuanzhuView();
                }
                break;
            case 2:
                Toast.makeText(getActivity(), "已互相关注", Toast.LENGTH_SHORT).show();
                if (!mGuanZhu) {
                    ShowGuanzhuView();
                }
                break;
            case -1:
                Toast.makeText(getActivity(), "关注错误", Toast.LENGTH_SHORT).show();
                break;
        }
        mGuanZhu = false;
    }

    private void ShowGuanzhuView() {
        if (recyclerView == null || videoList.size() == 0) {
            return;
        }
        View itemView = recyclerView.getChildAt(0);
        if (itemView == null) {
            return;
        }
        ImageView guanzhuImg = itemView.findViewById(R.id.opus_item_view_user_guanzhu);
        guanzhuImg.setVisibility(View.GONE);
    }

    @Override
    public void shoWorkData(HomeBean.DataBean data) {

    }

    @Override
    public void showFound(FoundAtBean data) {

    }

    @Override
    public void showVideoInfo(OpusBean opusBean) {

    }

    @Override
    public void showFocusInfo(RecommenResp attentRecommendbeans) {

    }

    @Override
    public void showNoFollowResult(FollowBean followBean, int position) {

    }

    @Override
    public void showState(BlindResp resp) {

    }

    @Override
    public void showJoinAdd(BlindResp resp) {
    }

    @Override
    public void showLogonResult() {

    }

    @Override
    public void zan(int type, int position, OpusBean opusBean) {
        if (!isToLogon) {
            if (!LogonUtils.chckLogon(getActivity(), false, 4)) {
                isToLogon = true;
                return;
            } else {
                if (type == 1) {
                    if (videoList.get(position).getIsLike() == 1) {
                        return;
                    }
                    mPresenter.getOpusZan(opusBean.getId() + "", "1", "", "1");
                    changeZan(true, position);
                } else {
                    mPresenter.getOpusZan(opusBean.getId() + "", "1", "", "0");
                    changeZan(false, position);
                }
            }
        }
    }

    @Override
    public void share(int position, OpusBean opusBean) {
        ShareFragment shareFragment = ShareFragment.newInstance();
        shareFragment.setLisenter(this);
        if (opusBean.getProfileId() == LogonUtils.getProFildId()) {
            shareFragment.setType("del");
        } else {
            shareFragment.setType("");
        }
        shareFragment.show(getActivity().getSupportFragmentManager(), "myFragment");
    }

    @Override
    public void join(int position, OpusBean opusBean) {
        if (null == opusBean){
            return;
        }
        mOpusBean = opusBean;
        LogUtils.e("test27", opusBean.toString());
        LogUtils.e(TAG, "开始下载:join");
        if (!LogonUtils.chckLogon(getActivity(), false, 4)) return;
        if (!isCanClickJoin) return;
        isCanClickJoin = false;
        LogUtils.e(TAG, "开始下载:join");
//        mPresenter.getJoin(opusBean.getId());
        mPresenter.getCostarVideoInfo(String.valueOf(opusBean.getId()));
    }

    @Override
    public void guanzhu(int position, OpusBean opusBean) {
        if (null == opusBean){
            return;
        }
        mPresenter.loginFollowFans(opusBean.getProfileId() + "");
    }

    @Override
    public void comm(int position, OpusBean opusBean) {
        CommentListDialogFragment fragment = CommentListDialogFragment.newInstance();
        fragment.setParam(position, opusBean.getId() + "", opusBean.getProfileId(), opusBean.getProfileName());
        fragment.setCommLisenter(this);
        fragment.show(getActivity().getSupportFragmentManager(), "myFragment");
    }

    @Override
    public void awkward(int position, OpusBean opusBean) {
        ObserverManager.getInstance().notifyObserver(ObserverListener.EVENT_AWKWARD, position, opusBean.getId());
    }


    @Override
    public void share(SHARE_MEDIA share_media, int type) {
        showLoading("正在分享...");
        OpusBean opusBean = videoList.get(currentPosition);
        ShareUtils.getIntance().shareVideo(getActivity(), share_media, String.valueOf(opusBean.getId()), opusBean.getVideoUrl(), opusBean.getVideoCverUrl(), TextUtils.isEmpty(opusBean.getProfileName())?"烤饭"+opusBean.getProfileId():opusBean.getProfileName() + ShareUtils.shareTitle, (TextUtils.isEmpty(opusBean.getVideoDesp()) ? ShareUtils.shareDes : opusBean.getVideoDesp()), this);
    }

    @Override
    public void playSuccess(int position) {
    }

    @Override
    public void other(int type) {
        OpusBean opusBean = videoList.get(currentPosition);
        switch (type) {
            case 1://复制链接
                ClipboardManager cm = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                // 将文本内容放到系统剪贴板里。
                String path = opusBean.getVideoUrl();
                ClipData myClip = ClipData.newPlainText("text", path);
                cm.setPrimaryClip(myClip);
                Toast.makeText(getActivity(), "链接已经复制到剪切板", Toast.LENGTH_SHORT).show();
                break;
            case 2:// 下载
                DownLoadVideo(opusBean.getVideoUrl());
                break;
            case 3://不感兴趣
                videoList.remove(opusBean);
                if (null != mAdapter) {
                    mAdapter.notifyDataSetChanged();
                }
                initPlay();
                mPresenter.getLoseInterest(opusBean.getId() + "", System.currentTimeMillis() + "");
                break;
            case 4:
                Navigate.startReportList(getContext(), 1, opusBean.getId());
                break;
            case 5://删除
                onDel(currentPosition, opusBean);
                break;
        }
    }

    // 下载
    private void DownLoadVideo(String url) {
        int permission = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission == PackageManager.PERMISSION_GRANTED) {
            downLoadProgressDialog = builder.setUrl(url).createDialog();
            downLoadProgressDialog.show();
        } else {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                downLoadProgressDialog = builder.setUrl(url).createDialog();
                downLoadProgressDialog.show();
            } else {
                ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
            }
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(getActivity()).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onShareFinish() {
        hideLoading();
    }

    @Override
    public void onShareSuccess() {

    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            long pos;
            switch (msg.what) {
                case SHOW_PROGRESS:
                    if (mPlayer == null || !mPlayer.isPlaying()) {
                        return;
                    }
                    setProgress();
                    mHandler.sendEmptyMessageDelayed(SHOW_PROGRESS, Constant.DEPLAY);
                    break;
                case 100:
                    if (v_progressBar != null && v_progressBar.getVisibility() == View.VISIBLE) {
                        v_progressBar.setVisibility(View.INVISIBLE);
                    }
                    break;
                case 10000:
                    play();
                    break;
                case 10001:
                    if (mAdapter != null) {
                        mAdapter.startPlay(currentPosition);
                    }
                    break;
            }
        }
    };

    private long setProgress() {
        if (mPlayer == null) {
            return 0;
        }

        long position = mPlayer.getCurrentPosition();
        long duration = mPlayer.getDuration();
        videoPlayTimes = (int) position;
        if (videoPlayCount > 1) {
            videoPlayTimes = (int) duration;
        }

        if (progressBar != null) {
            if (duration > 0) {
                progressBar.setProgress((int) position);
                progressBar.setMax((int) duration);
            }
        }
        if (position + 200 >= duration) {
            getCostarList();
        }
        showCurrentCostarPro((int) position);
        return position;
    }

    public void getCostarList() {
        videoSectionList.clear();
        if (videoList == null || videoList.size() == 0 || currentPosition > videoList.size()) {
            return;
        }
        if (cosRel == null || cosCircleImageView == null || cosGuanzhu == null || cosTag == null) {
            getCosView();
        }
        int proFildId = videoList.get(currentPosition).getProfileId();
        for (VideoSection v : videoList.get(currentPosition).getVideoSectionInfoList()) {
            if (v.getCostarProfileId() != proFildId) {
                videoSectionList.add(v);
            }
        }
        if (videoSectionList.size() == 0) {
            if (null == cosRel){
                return;
            }
            cosRel.setVisibility(View.GONE);
        }
    }
    public void showCurrentCostarPro(int position) {
        if (cosRel == null || cosCircleImageView == null || cosGuanzhu == null || cosTag == null) {
            getCosView();
        }
        if (videoSectionList == null || videoSectionList.size() == 0) {
            opus_item_view_user_img1.setColorFilter(null);
            cosCircleImageView.setColorFilter(grayColorFilter);
            return;
        }
        int s_time = 0;
        int e_time = 0;
        VideoSection videoSection = null;
        videoSection = videoSectionList.get(0);
        if (videoSection == null) {
            return;
        }
        e_time = videoSection.getSectionEndPoint();

        if (e_time < position) {
            videoSectionList.remove(0);
            if (videoSectionList.size() > 0) {
                videoSection = videoSectionList.get(0);
            }
        }
        if (videoSection == null) {
            return;
        }
        s_time = videoSection.getSectionStartPoint();
        e_time = videoSection.getSectionEndPoint();

        int cosUserId = videoSection.getCostarProfileId();
        Log.e("test41", s_time + "--" + position + "--" + e_time);
        if (s_time > position) {
            if (cosTag.getTag() == null || cosUserId != Integer.parseInt(cosTag.getTag().toString())) {
                cosTag.setTag(cosUserId);
                ImageUtils.LoadImage(getActivity(), videoSection.getCostarProfileAvatar(), cosCircleImageView);
                if (videoSection.getIsAttentionCostar() == 1) {
                    cosGuanzhu.setVisibility(View.INVISIBLE);
                } else {
                    cosGuanzhu.setVisibility(View.VISIBLE);
                }
                if (videoSection.getCostarTag() != null && !"".equals(videoSection.getCostarTag())) {
                    cosTag.setText(videoSection.getCostarTag());
                    cosTag.setVisibility(View.INVISIBLE);
                } else {
                    cosTag.setVisibility(View.INVISIBLE);
                }
            }
            cosCircleImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle bundle = new Bundle();
                    bundle.putInt("user_id", cosUserId);
                    bundle.putInt("tag", 1);
                    TerminalActivity.showFragment(getActivity(), HomeMineFragment.class, bundle);
                }
            });
            cosGuanzhu.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!LogonUtils.chckLogon(getActivity(), false, 4)) return;
                    mGuanZhu = true;
                    mPresenter.loginFollowFans(cosUserId + "");
                    handleCosGuanzhu(cosUserId);
                    cosGuanzhu.setVisibility(View.INVISIBLE);
                }
            });
            tofocus(cosUserId);
            opus_item_view_user_img1.setColorFilter(null);
            cosCircleImageView.setColorFilter(grayColorFilter);
            Log.e("test41", "------未开始播放");
            cosRel.setVisibility(View.VISIBLE);
            return;
        }
        if (e_time > position) {
            if (cosTag.getTag() == null || cosUserId != Integer.parseInt(cosTag.getTag().toString())) {
                cosTag.setTag(cosUserId);
                ImageUtils.LoadImage(getActivity(), videoSection.getCostarProfileAvatar(), cosCircleImageView);
                if (videoSection.getIsAttentionCostar() == 1) {
                    cosGuanzhu.setVisibility(View.INVISIBLE);
                } else {
                    cosGuanzhu.setVisibility(View.VISIBLE);
                }
                if (videoSection.getCostarTag() != null && !"".equals(videoSection.getCostarTag())) {
                    cosTag.setText(videoSection.getCostarTag());
                    cosTag.setVisibility(View.INVISIBLE);
                } else {
                    cosTag.setVisibility(View.INVISIBLE);
                }
            }
            tofocus(cosUserId);
            cosCircleImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle bundle = new Bundle();
                    bundle.putInt("user_id", cosUserId);
                    bundle.putInt("tag", 1);
                    TerminalActivity.showFragment(getActivity(), HomeMineFragment.class, bundle);
                }
            });
            cosGuanzhu.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!LogonUtils.chckLogon(getActivity(), false, 4)) return;
                    mGuanZhu = true;
                    mPresenter.loginFollowFans(cosUserId + "");
                    handleCosGuanzhu(cosUserId);
                    cosGuanzhu.setVisibility(View.INVISIBLE);
                }
            });
            opus_item_view_user_img1.setColorFilter(grayColorFilter);
            cosCircleImageView.setColorFilter(null);
            Log.e("test41", "---开始播放");
            cosRel.setVisibility(View.VISIBLE);
            return;
        }
    }
    void tofocus(int cosUserId){
        AppListener.getInstance().setOnFocusBackListener(new AppListener.OnFocusBackListener() {
            @Override
            public void onFocusBack(String focus) {
                mProfileId = focus.split("::");
            }
        });
        if (null !=mProfileId) {
            if (mProfileId[0].equals(String.valueOf(cosUserId))) {
                if ("1".equals(mProfileId[1])) {
                    cosGuanzhu.setVisibility(View.GONE);
                } else if ("2".equals(mProfileId[1])) {
                    cosGuanzhu.setVisibility(View.VISIBLE);
                }
            }
        }
    }
    @Override
    public void onPlay() {
        if (netStatusDialog != null)
            netStatusDialog.dismiss();
        canPlay = true;
        play();
    }

    // 网络错误重新播放
    @Override
    public void onRefreshPlay() {
        if (netStatusDialog != null)
            netStatusDialog.dismiss();
        play();
    }

    // 网络错误重新请求
    @Override
    public void onNetRefresh() {
        if (null != coverImgUrl) {
            return;
        }
        mPresenter.getOpusList(pageNo + "");
        if (netStatusDialog != null)
            netStatusDialog.dismiss();
    }

    private void showNetType(int type, String des, String nextStr) {
        if (null == netBuilder) {
            return;
        }
        netStatusDialog = netBuilder.setMessage(type, des, nextStr).setItemClickListener(this).createDialog();
        if (!AppUtils.isShowNetDialog()) return;
        netStatusDialog.show();
    }

    //不喜欢作品
    @Override
    public void onUnlike(int position, OpusBean opusBean) {
        videoList.remove(opusBean);
        if (null != mAdapter) {
            mAdapter.notifyDataSetChanged();
        }
        initPlay();
        mPresenter.getLoseInterest(opusBean.getId() + "", System.currentTimeMillis() + "");
    }

    void initPlay() {
        if (currentPosition > 0 && currentPosition < videoList.size()) {
            mLayoutManager.scrollToPositionWithOffset(currentPosition, 0);
            mLayoutManager.setStackFromEnd(true);
        }
        play();
    }

    //举报作品
    @Override
    public void onReport(int position, OpusBean opusBean) {
        if (LogonUtils.chckLogon(getActivity(), false, 0)) {
            Navigate.startReportList(getContext(), 1, opusBean.getId());
        }
    }

    //删除作品
    @Override
    public void onDel(int position, OpusBean opusBean) {
        try {
            mAdapter.stopPlay(position);
            videoList.remove(position);
            mAdapter.notifyDataSetChanged();
            mPresenter.del(opusBean.getId() + "");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //评论成功 回调更新评论数量
    @Override
    public void commSuccess(int position, int type) {
        if (position > videoList.size()) {
            return;
        }
        int count = videoList.get(position).getCommentCount();
        if (type == 1) {
            count++;
        } else {
            count--;
        }
        videoList.get(position).setCommentCount(count);

        if (recyclerView == null || videoList.size() == 0) {
            return;
        }
        View itemView = recyclerView.getChildAt(0);
        if (itemView == null) {
            return;
        }
        final TextView tv_comment = itemView.findViewById(R.id.opus_item_view_comment);
        tv_comment.setText(StringUtils.formatZanCount(count));
    }

    boolean sharkFlag = true;

    //摇一摇
    public void shark() {
        sharkFlag = !sharkFlag;
        if (mAdapter != null) {
            mAdapter.setSharkFlag(sharkFlag);
            mAdapter.notifyDataSetChanged();
            play();
        }
    }

    //合演关注 改变关注状态
    public void handleCosGuanzhu(int id) {
        if (videoList.get(currentPosition).getVideoSectionInfoList() != null) {
            for (int i = 0; i < videoList.get(currentPosition).getVideoSectionInfoList().size(); i++) {
                if (videoList.get(currentPosition).getVideoSectionInfoList().get(i).getCostarProfileId() == id) {
                    videoList.get(currentPosition).getVideoSectionInfoList().get(i).setIsAttentionCostar(1);
                }
            }
        }
    }

    //上报评分
    private void sendGrade(String video_id, int video_time) {
        if (!TextUtils.isEmpty(VideoUtils.video_grade.get("videoId"))) {
            return;
        }
        long timestamp = System.currentTimeMillis();
        mPresenter.grade(video_id, timestamp, video_time);
        VideoUtils.video_grade.put(video_id, "1");
    }

    //在列表中插入我的视频
    public void addMyVideo(OpusBean opusBean) {
        mPresenter.getJoin(opusBean.getId());
        try {
//            OpusBean bean = new OpusBean();
//            bean.setProfileId(joinCostarBean.getProfileId());
//            List<VideoSection> videoSectionInfoList = new ArrayList<>();
//            for (VideoSectionBean b : joinCostarBean.getVideoSectionInfos()) {
//                VideoSection v = new VideoSection();
//                v.setCostarProfileId(b.getOriginalProfileId());
//                v.setSectionStartPoint((int) b.getSectionStartPoint());
//                v.setSectionEndPoint(b.getSectionEndPoint());
//                v.setId(b.getId());
//                v.setCreateTime(b.getCreateTime());
//                v.setSectionVideoSpan(b.getSectionVideoSpan());
//                v.setSectionVideoUrl(b.getSectionVideoUrl());
//                v.setSectionVideoDesp(b.getSectionVideoDesp());
//                videoSectionInfoList.add(v);
//            }
//            bean.setVideoSectionInfoList(videoSectionInfoList);
//            bean.setVideoDesp(joinCostarBean.getVideoDesp());
//            bean.setProfileAvatar(LogonUtils.getNickIcon());
//            bean.setVideoCverUrl(joinCostarBean.getVideoCverUrl());
//            bean.setVideoUrl(joinCostarBean.getVideoUrl());
//            bean.setActivityTitle(joinCostarBean.getActivityTitle());
//            bean.setIsActivity(joinCostarBean.getIsActivity());
//            bean.setId(joinCostarBean.getId());
//            LogUtils.e("test27", bean.toString());
            if (null != videoSectionList) {
                videoSectionList.clear();
            }
            currentPosition = currentPosition+1;
            videoList.add(currentPosition, opusBean);
            mAdapter.clearPlayer();
            mAdapter.notifyDataSetChanged();
            mLayoutManager.scrollToPositionWithOffset(currentPosition, 0);
            mLayoutManager.setStackFromEnd(true);
            play();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void ActivityClick(OpusBean opusBean) {
        Navigate.gotoActivityDetail(getActivity(), Url.ACTIVITY_URL, opusBean.getActivityId());
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.cosfun_iv:
                Navigate.gotoSearchActivity(getActivity());
                break;
        }
    }

    @Override
    public void remmend(int position, OpusBean opusBean) {
        if (StringUtils.isFastDoubleClick(500)){
            return;
        }
        manager = 2;
        mPresenter.checkAndRemmend(String.valueOf(opusBean.getId()),2);
    }

    @Override
    public void checkAndPass(int position, OpusBean opusBean) {
        if (StringUtils.isFastDoubleClick(500)){
            return;
        }
        manager = 1;
        mPresenter.checkAndRemmend(String.valueOf(opusBean.getId()),1);
    }

    @Override
    public void showCheckAndRemmend() {
        if (2 == manager){
            showToast(getResources().getString(R.string.recommend_success));
        }else if (1 == manager){
            showToast(getResources().getString(R.string.check_success));
        }
    }
    @Override
    public void startPlay() {
        if (null == mHandler){
            return;
        }
        mHandler.removeMessages(SHOW_PROGRESS);
        mHandler.sendEmptyMessageDelayed(SHOW_PROGRESS, 100);
    }

}
